import { GET_TAG_TREE, GET_FUNCTIONALITIES, SAVE_USER_INFO } from '__STORE__/operation-type'
import { uploadArticleCover, uploadArticleImage } from '__SERVICE__/files.js'
import { publishArticle } from '__SERVICE__/article.js'
import MavonEditorMxin from '__COMPONENTS__/mavon_editor/base-mixin.js'
// const $SERVER_URL = 'http://127.0.0.1:7001'
const $SERVER_URL = process.env.VUE_APP_SERVICE_API

export default {
  mixins: [MavonEditorMxin],
  name: 'MyMavonEditor',
  data: () => ({
    markdownValue: '',
    tagTree: null,
    checkTagclass: null,
    functionalities: [],
    checkedTags: [],
    attPopUpShow: false,
    publishPopUpShow: false,
    functionalityId: undefined
  }),
  created() {
    this.getTags()
    this.getFunctionalities()
  },
  mounted() {

  },
  methods: {
    async getTags() {
      try {
        const dataRsource = this.$store.state.globalConfig
        //如果没有等待 获取数据
        if(!dataRsource.tagTree ) await this.$store.dispatch(GET_TAG_TREE)
        //成功获取数据
        const tagclasses = dataRsource.tagTree
        this.tagTree = Object.freeze(tagclasses)
        this.checkTagclass = tagclasses[0] && tagclasses[0].tag_models
      }catch(e) {
        console.log(e.message)
      }
    },
    async getFunctionalities() {
      try {
        const dataRsource = this.$store.state.globalConfig
        //如果没有等待 获取数据
        if(!dataRsource.functionalities ) await this.$store.dispatch(GET_FUNCTIONALITIES)
        //成功获取数据
        const functionalities = dataRsource.functionalities 
        this.functionalities = Object.freeze(functionalities)
      }catch(e) {
        console.log(e.message)
      }
    },
    //切换tagclass的逻辑 start
    changeTagclass(e) {
      const target = e.target
      if(target.className === 'tagclass') {
        const index = target.dataset.index
        this.checkTagclass = this.tagTree[index].tag_models
      }
    },
    //切换tagclass的逻辑 end
    //选择tag的逻辑 start
    checkTag(e) {
      if(this.checkedTags.length >= 3) {
        this.$Notice.state({title: '操作失败', desc: '最多只能三个', duration: 3000})
        return false
      }
      const target = e.target
      if(target.className === 'tag') {
        const index = target.dataset.index
        this.checkedTags.push(Object.freeze(this.checkTagclass[index]))
        this.checkTagclass.splice(index, 1)
      }
    },
    //选择tag的逻辑 end
    // 取消选择tag的逻辑 start
    cancelCheckTag(e) {
      const target = e.target
      if(target.className === 'checked-tag') {
        const index = target.dataset.index
        this.checkTagclass.push(this.checkedTags[index])
        this.checkedTags.splice(index, 1)
      }
    },
    // 取消选择tag的逻辑 end
    //真正提交发布文章的地方 start
    async publish() {
      const { user_id, access_token } = this.$store.state.user.deadUserInfo
      if(!user_id || !access_token) {
        this.$Notice.state({title: '权限不允许', desc: '请先登入', duration: 3000})
        this.publishPopUpShow = false
        return
      }
      const content = this.markdownValue //内容
      const functionality_id = this.functionalityId
      const headline = this.$refs['headline'].value
      const outline = this.$refs['outline'].value
      const cover_url = this.$refs['cover_url'].style.backgroundImage.match(/url\("(\S*)"\)/)[1]
      const tag_ids = this.checkedTags.map((tag)=>{
        return tag.id
      })
      const result = await publishArticle({
        content, headline, outline, cover_url, tag_ids, functionality_id,
        user_id, access_token
      })
      this.$store.dispatch(SAVE_USER_INFO, {
        access_token: result.data.access_token
      })
      this.$router.push({name: 'Mine'})
      this.publishPopUpShow = false
    },
    //真正提交发布文章的地方 end
    async uploadArticleCover(e, data) {
      const target = e.target
      const formdata = this.getFileFormData(target)
      try {
        const result = await uploadArticleCover(formdata)
        const {data: {upload_url}} = result
        this.$refs['cover_url'].style.backgroundImage = `url(${$SERVER_URL + upload_url})`
        this.$refs['cover_url'].innerHTML = ''
      }catch(e) {
        console.log(e)
      }
    },
    // 获取文件的 fromdata形式 start
    getFileFormData(target) {
      const file = target.files[0]
      const fileName = file.name
      const fileSuffixIndex = fileName.lastIndexOf('.')
      const filePreffix = fileName.slice(0, fileSuffixIndex)
      const fileSuffix = fileName.slice(fileSuffixIndex+1)
      if('jpg png jpeg gif'.indexOf(fileSuffix) === -1) { // 文件格式无法匹配
        this.$Notice.error({title: '格式有误', desc: '只允许：jpg / png / jpeg / gif / ico', duration: 3000})
        return null
      }
      const formdata = new FormData()
      formdata.append(filePreffix, file)
      return formdata
    },
    // 获取文件的 fromdata形式 end

    //上传markdown文件
    $imgAdd(pos, $file) {
      const formdata = new FormData();
      formdata.append("image", $file);
      const result = await uploadArticleImage(formdata)
      const {data: {upload_url}} = result
      this.$refs.mavonEditor.$img2Url(pos, $SERVER_URL + upload_url);
    },
  }
}